package com.java.base.thread;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.locks.ReentrantLock;

public class TestJMM {


    public static void main(String[] args) throws InterruptedException {
//        test1();
        test2();
    }

    static class InnerTest {

//        private volatile boolean flag = false;
        private boolean flag = false;
        private volatile int a = 0;

        public void refresh() {
            this.flag = true;
            System.out.println("change");
        }


        public void load() {
            while (!flag) {
                //操作volatile到变量也会触发刷新线程内存副本到主内存，调用System.out.print的方法会触发，print方法操作了volatile变量
//                System.out.print("-");
//                a++;
            }
            System.out.println("END");
        }
    }


    public static void test2() throws InterruptedException {
        InnerTest testJMM2 = new InnerTest();
        Thread a = new Thread(testJMM2::refresh);
        Thread b = new Thread(testJMM2::load);

        b.start();
        Thread.sleep(1000);
        a.start();
    }


    //    static AtomicInteger a = new AtomicInteger(0);
//    static volatile int a = 0;
    static int a = 0;

    public static void test1() throws InterruptedException {

        int max = 1000;
        int threadMax = 100;
        ReentrantLock lock = new ReentrantLock();

        List<Thread> list = new ArrayList<>(threadMax);

        for (int i = 0; i < threadMax; i++) {
            Thread t = new Thread(() -> {
                for (int j = 0; j < max; j++) {
//                    lock.lock();
//                    a.addAndGet(1);
                    a++;
//                    lock.unlock();
                }
            });
            t.start();
            list.add(t);
        }

        for (Thread t : list) {
            while (t.isAlive()) {
                Thread.sleep(500);
            }
        }

        System.out.println(max * threadMax);
        System.out.println(a);

    }
}
